<script setup>
import { Check, Close, Edit, SwitchButton, Warning } from '@element-plus/icons-vue';
import { get,put,getImage, formPost } from '../api/http'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted } from 'vue';
import { menuStore, loginStatus } from '../utils/store';

const router = useRouter()
const userInfo = ref({})
const updateUserInfo = ref({})
const showEditDialog = ref(false)
const avtiveName = ref('baseInfo')
const avatarData = ref(null)
const oldPassword = ref('')
const newPassword = ref('')
const showEnableMail = ref(false)
const vaildCode = ref('')
const loading = ref(false)
const showSetAvatarDialog = ref(false)
const avatarBase64 = ref(null)
const cropper = ref(null)

const logout = () => {
    get('logout').then(res=>{
        if(res.status){
            localStorage.setItem('loginStatus', 'no')
            localStorage.removeItem('token')
            get('menu').then(res=>{
                menuStore.menuList = res.data
            })
            loginStatus.value = false
            router.push('/')
        }else{
            ElMessage({type: 'error', message: res.msg})
        }
    })
}

const getUserInfo = () => {
    get('user/userInfo').then(res=>{
        if(res.status){
            userInfo.value = res.data
        }else{
            ElMessage({type: 'error', message: res.msg})
        }
    })
}

const getUserAvatar = () => {
    getImage('user/avatar').then(res=>{
        avatarData.value = window.URL.createObjectURL(res);
    })
}

const edit = () => {
    updateUserInfo.value.id = userInfo.value.id
    updateUserInfo.value.nickName = userInfo.value.nickName
    updateUserInfo.value.gender = userInfo.value.gender
    updateUserInfo.value.birthday = userInfo.value.birthday
    showEditDialog.value = true
}

const setUserInfo = () => {
    put('user/setUserInfo',updateUserInfo.value).then(res=>{
        ElMessage({
            type: res.status?'success':'error',
            message: res.msg
        })
        if(res.status){
            showEditDialog.value = false
            getUserInfo();
        }
    })
}

const resetPassword = () => {
    put('user/setUser', {oldPassword: oldPassword.value, newPassword: newPassword.value}).then(res=>{
        ElMessage({type: res.status ? 'success':'error', message: res.msg})
        if(res.status){
            localStorage.removeItem('token');
            localStorage.setItem('loginStatus','no')
            router.push('/login')
        }
    })
}

const enableMail = () => {
    ElMessageBox.confirm('该操作将会向你的邮箱发送激活吗，是否继续？','提示',{confirmButtonText:'确定',cancelButtonClass:'取消',type:'warning'}).then(()=>{
        loading.value = true
        get('user/enableEmail').then(res=>{
            ElMessage({type:res.status?'success':'error',message:res.msg})
            if(res.status){
                showEnableMail.value = true;
            }
            loading.value = false
        })
    })
    
}

const rotateLeft = () => {
    cropper.value.rotateLeft();
}

const rotateRight = () => {
    cropper.value.rotateRight();
}

const submitEnableMail = () => {
    if(vaildCode.value == ''){
        ElMessageBox.alert('请输入验证码','提示',{type:'warning'})
    }else{
        get('user/enableEmail',{enableCode:vaildCode.value}).then(res=>{
            ElMessage({type:res.status?'success':'error',message:res.msg})
            if(res.status){
                showEnableMail.value = false
                getUserInfo()
            }
        })
    }
}

const getPickAvatar = () => {
    cropper.value.getCropBlob((data) => {
        let param = new FormData();
        param.append("file", data);
        formPost('user/setAvatar',param).then((res) => {
          ElMessage({
            type: res.data.status ? "success" : "error",
            message: res.data.msg,
          });
          if (res.data.status) {
            avatarData.value = window.URL.createObjectURL(data);
          }
          showSetAvatarDialog.value = false;
        });
      });
}

const selectFile = (e) => {
    var file = e.target.files[0];
    var filesize = file.size;
    var filename = file.name;
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
        var imgcode = e.target.result;
        avatarBase64.value = imgcode
        showSetAvatarDialog.value = true;
    }
}

const changeAvatar = () => {
    document.getElementById('avatarFile').click()
}

onMounted(()=>{
    getUserInfo();
    getUserAvatar()
})

</script>
<template>
    <main v-blog-title data-title="个人信息" v-loading="loading">
        <el-row justify="center" style=" height: calc(100vh - 60px); align-items: center;">
            <el-col :lg="12" :md="12" :xl="12" :xs="22">
                <el-card>
                    <div class="headInfo">
                        <input id="avatarFile" type="file" hidden @change="selectFile" />
                        <el-avatar @click="changeAvatar" :src="avatarData" shape="square" style="background-color: #fff; cursor: pointer; border: 1px solid #eee;" size="large"></el-avatar>
                        <div class="username">{{ userInfo.username }}</div>
                    </div>
                    <div class="userInfo">
                        <div class="info">
                            <label>用户名:</label>
                            <div class="user-info-item">{{userInfo.username}}</div>
                        </div>
                        <div class="info">
                            <label>昵称:</label>
                            <div class="user-info-item">{{userInfo.nickName}}</div>
                        </div>
                        <div class="info">
                            <label>邮箱:</label>
                            <div class="user-info-item">{{userInfo.email}}</div>
                        </div>
                        <div class="info">
                            <label>性别:</label>
                            <div class="user-info-item">
                                {{userInfo.gender == 0 ? '男' : (userInfo.gender == 1 ? '女' : '其他')}}</div>
                        </div>
                        <div class="info">
                            <label>年龄:</label>
                            <div class="user-info-item">{{userInfo.age}}</div>
                        </div>
                        <div class="info">
                            <label>生日:</label>
                            <div class="user-info-item">{{userInfo.birthday}}</div>
                        </div>
                        <div class="info">
                            <label>邮箱状态:</label>
                            <div class="user-info-item">
                                <span v-if="userInfo.emailStatus">已验证</span>
                                <el-link type="warning" v-if="!userInfo.emailStatus" @click="enableMail">未验证(点击激活)</el-link>
                            </div>
                        </div>
                        <div class="option" style="text-align: center; margin-top: 20px;">
                            <el-button @click="edit" :icon="Edit" type="default" plain style="width: 50%;" >修改信息</el-button>
                            <el-button @click="logout" :icon="SwitchButton" type="danger" plain style="width: 50%;">退出账号</el-button>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="showEditDialog" :close-on-click-modal="false" width="30%">
            <el-tabs v-model="avtiveName">
                <el-tab-pane label="基本资料" name="baseInfo">
                    <el-form>
                        <el-form-item label="昵称">
                            <el-input v-model="updateUserInfo.nickName" placeholder="输入昵称"></el-input>
                        </el-form-item>
                        <el-form-item label="性别">
                            <el-select style="width:100%" placeholder="请选择性别" v-model="updateUserInfo.gender">
                                <el-option label="男性" :value="0"></el-option>
                                <el-option label="女性" :value="1"></el-option>
                                <el-option label="其他" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="生日">
                            <el-date-picker v-model="updateUserInfo.birthday" placeholder="选择出生日期" value-format="YYYY-MM-DD"></el-date-picker>
                        </el-form-item>
                    </el-form>
                    <div class="dialogOption">
                        <el-button @click="showEditDialog=false" :icon="Close">取消</el-button>
                        <el-button @click="setUserInfo" type="primary" :icon="Check">完成</el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="重设密码" name="account">
                    <div style="display: flex; flex-direction: column; align-items: center;">
                        <el-input v-model="oldPassword" style="margin: 0 10px;" type="password" placeholder="旧密码"></el-input>
                        <el-input v-model="newPassword" style="margin: 10px;" type="password" placeholder="新密码"></el-input>
                        <el-button style="width:100%;" @click="resetPassword" type="primary">更新</el-button>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
        <el-dialog title="邮箱验证" v-model="showEnableMail" :close-on-click-modal="false">
            <p>请检查您的注册邮箱，获取验证码后输入到下方进行验证</p>
            <el-input v-model="vaildCode" style="width: 300px;" placeholder="输入验证码"></el-input>
            <el-button @click="submitEnableMail" style="margin-left:10px;">验证</el-button>
        </el-dialog>
        <el-dialog title="头像设置" v-model="showSetAvatarDialog" width="400">
            <div class="cropperBox">
                <vue-cropper :fixedBox="true" :canMoveBox="false" :autoCrop="true" autoCropWidth="200" autoCropHeight="200" ref="cropper" :img="avatarBase64" outputType="png"></vue-cropper>
            </div>
            <div class="optionBtn">
                <el-button @click="rotateLeft" style="width:100px;"><i class="fa fa-rotate-left"></i>左旋转</el-button>
                <el-button @click="rotateRight" style="width:100px;"><i class="fa fa-rotate-right"></i>右旋转</el-button>
                <el-button @click="getPickAvatar" type="primary" style="width:100px;"><i class="fa fa-save"></i>保存</el-button>
            </div>
        </el-dialog>

    </main>
</template>
<style scoped>
main{
    background-color: var(--el-color-default);
    height: calc(100vh - 60px);
}
.headInfo{
    display: flex;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #aaa;
}
.username{
    font-weight: bold;
    font-size: 20px;
    padding-left: 10px;
}
label{
    display: inline-block;
    width: 100px;
    font-weight: bold;
}
.info{
    display: flex;
    padding: 10px;
    border-bottom: 1px solid #ccc;
}
.user-info-item{
    padding-left: 10px;
}
.option{
    display: flex;
    align-items: center;
}
.dialogOption{
    display: flex;
    align-items: center;
    justify-content: end;
}
.cropperBox {
    width: 100%;
    height: 300px;
}
.optionBtn{
    margin-top: 10px;
    text-align: center;
}
</style>